<?php
namespace App\Logic;

class AdminLogic
{
    public $m;
    public function __construct()
    {
        $this->m = M('admin');
    }

    public function ls()
    {
        //列表
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $page = max($page, 1);
        $size = isset($_POST['size']) ? $_POST['size'] : 15;
        $start = $page * $size - $size;

		$_POST['role'] && $where[] = "role = '{$_POST['role']}'";
		$_POST['name'] && $where[] = "name LIKE '%{$_POST['name']}%'";
		$_POST['user'] && $where[] = "user LIKE '%{$_POST['user']}%'";
		$_POST['mobile'] && $where[] = "mobile LIKE '%{$_POST['mobile']}%'";
		$_POST['email'] && $where[] = "name LIKE '%{$_POST['email']}%'";
		$_POST['nickname'] && $where[] = "nickname LIKE '%{$_POST['nickname']}%'";


        $where = $where ? implode(' AND ', $where) : '';
        
        $data = $this->m->where($where)->order('id desc')->limit($start, $size)->select();
        $total = $this->m->where($where)->count();
        
        return array('st' => 1, 'data' => $data, 'total' => $total);
    }
    
    public function get($id)
    {
        $id = (int) $id;
        $row = $this->m->find($id);
		if(!$row['avatar']) $row['avatar'] = '/static/image/avatar_man.gif';
        return array('st' => 1, 'data' => $row);
    }
    
    public function delete($id)
    {
        $rs = $this->m->where("id = $id")->delete();
        if($rs === false) {
            json(0, '删除失败');
        }
    }

	//编辑自己信息
	public function edit($post)
	{
		$id = (int) $post['id'];
		if($id != ADMIN_ID) json(0, '参数错误');
		if($post['change_pwd'] == '1') {
			$old = $this->m->where(['id' => $id])->find();
			if($old['pwd'] != md5($post['old_pwd'])) {
				json(0, '旧密码错误');
			}
			$post['pwd'] = md5($post['new_pwd']);
		}
		if($id) {
			unset($post['user']);
			$rs = $this->m->where("id = $id")->save($post);
		}else{
			$rs = $this->m->add($post);
		}
		if($rs === false) {
			json(0, '保存失败');
		}
	}

	//管理员编辑用户信息
    public function save($post)
    {
        $id = (int) $post['id'];
		if($post['new_pwd']) {
			$post['pwd'] = md5($post['new_pwd']);
		}
        if($id) {
            $rs = $this->m->where("id = $id")->save($post);
        }else{
            $rs = $this->m->add($post);
        }
		if($rs === false) {
			json(0, '保存失败');
		}
    }

	//修改状态
	public function st($id, $st)
	{
		$rs = $this->m->where("id = $id")->setField('st', $st);
		if($rs !== false) {
			return array('st' => 1);
		}else{
			return array('st' => 0, 'msg' => '修改状态错误');
		}
	}

	public function del($id)
	{
		$id = (int) $id;
		if(!$id) json(0, '参数错误');
		$rs = $this->m->where("id = $id")->delete();
		if($rs === false) {
			json(0, '删除失败');
		}else{
			json(1);
		}
	}
}